﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
using System.Diagnostics.Contracts;

namespace UnitTestUtils.DB
{
    /// <summary>
    /// Wrapps <see cref="IDbConnection"/> interface and provides additional cleanup functionality
    /// when the connection is closed.
    /// </summary>
    public class SqlCeConnectionWrapper : IDisposable
    {
        string _filename;

        /// <summary>
        /// Wrapps SqlCeConnection and cleans up the related db file after the connection has been closed.
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="filename"></param>
        public SqlCeConnectionWrapper(IDbConnection connection, string filename)
        {
            Contract.Requires<ArgumentNullException>(connection != null, "connection");
            Contract.Requires<ArgumentException>(!string.IsNullOrWhiteSpace(filename), "filename");

            this.Connection = connection;
            _filename = filename;
        }

        /// <summary>
        /// The connection.
        /// </summary>
        public IDbConnection Connection { get; private set; }

        #region IDisposable Members
        /// <summary>
        /// Dispose.
        /// </summary>
        public void Dispose()
        {
            if (this.Connection.State == ConnectionState.Open)
                this.Connection.Close();

            if (File.Exists(_filename))
            {
                File.Delete(_filename);
            }
        }

        #endregion
    }
}
